package str

import (
	"fmt"
	"strings"
)

func validTicTacToe(board []string) bool {

	chessMap := map[string]int{
		"X": 0,
		"O": 0,
	}

	chess := [3][]string{}
	for i := 0; i < 3; i++ {
		chess[i] = strings.Split(board[i], "")
		for _, v := range chess[i] {
			if _, ok := chessMap[v]; ok {
				chessMap[v]++
			}
		}
	}

	// 必须：X可以等于O，或者X等于O+1
	if chessMap["X"] > chessMap["O"]+1 || chessMap["O"] > chessMap["X"] {
		return false
	}

	// 都没下
	if chessMap["X"]+chessMap["O"] == 0 {
		return true
	}

	finishX := checkWin(chess, "X")
	finishO := checkWin(chess, "O")
	fmt.Println(finishX, finishO)

	// 两个都赢了或者都没赢的同时没有死棋
	if finishX && finishO {
		return false
	}

	// X赢得时候必须 X==O+1
	if finishX && !finishO && chessMap["X"] != chessMap["O"]+1 {
		return false
	}
	// X赢得时候必须 X==O
	if !finishX && finishO && chessMap["X"] != chessMap["O"] {
		return false
	}

	fmt.Println("true")
	return true
}

func checkWin(board [3][]string, chess string) bool {

	for i := 0; i < 3; i++ {
		// 横
		if board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][2] == chess {
			return true
		}
		// 竖
		if board[0][i] == board[1][i] && board[2][i] == board[1][i] && board[2][i] == chess {
			return true
		}
	}

	if board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[2][2] == chess {
		return true
	}

	if board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[2][0] == chess {
		return true
	}

	return false

}
